<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { toNumber } from 'lodash-es'
import qs from 'qs'
import { GetChancesourceData, PostDeleteData, PostSenddrawchanceData } from '@/api/modules/drawactuser'
import { GetOptionData } from '@/api/modules/subscriber'

// const imgDomain = 'https://img1.eprhan.cc'
const route = useRoute()

const findFrom = ref({
  FromUserId: '',
  FromOrderNo: '',
})
const dataList: any = reactive({
  list: [],
})
const loading = ref(true)
const total = ref(0)
let PageSize = 20

const userMessage = ref({
  userId: 0,
  userNickName: '',
  userPhone: '',
  scOpenId: '',
})

async function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    DrawId: route.query.drawId,
    UserId: route.query.UserId,
    ...(findFrom.value.FromUserId && ({ FromUserId: findFrom.value.FromUserId })),
    ...(findFrom.value.FromOrderNo && ({ FromOrderNo: findFrom.value.FromOrderNo })),
  }
  await GetChancesourceData(params).then(async (dataRes: any) => {
    if (dataRes.succeeded) {
      dataList.list = dataRes.data.items
      total.value = dataRes.data.total
      loading.value = false
    }
    else {
      loading.value = false
      ElMessage.error(`获取数据失败。${dataRes.errors}`)
    }
  })
  loading.value = false
}

async function GetUserData() {
  // const params = qs.stringify({ UserId: route.query.UserId })
  const params = qs.stringify({ UserIdList: [route.query.UserId] })
  await GetOptionData(params).then((res: any) => {
    if (res.succeeded) {
      userMessage.value = res.data[0]
    }
  })
}
// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 发送抽奖机会
const dialogViewDetails = ref(false)

const ruleFormRef = ref<FormInstance>()
interface Required {
  helpSource: number
  userId: number | string
  drawId: number | string
  orderNo: string
  getNums: number
}
const RequiredId = ref<Required>({
  helpSource: 3,
  userId: 0,
  drawId: 0,
  orderNo: '',
  getNums: 1,
})
const rules = reactive<FormRules>({
  getNums: [
    { required: true, message: '请输入抽奖次数', trigger: 'blur' },
  ],
  drawId: [
    { required: true, message: '请输入抽奖活动ID', trigger: 'blur' },
  ],
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
  ],
  orderNo: [
    { required: true, message: '请输入订单编号', trigger: 'blur' },
  ],
})

function OpenView() {
  dialogViewDetails.value = true
}

async function submitForm(formEl: FormInstance | undefined) {
  if (!formEl) {
    return
  }
  await formEl.validate((valid) => {
    if (valid) {
      RequiredId.value.drawId = toNumber(RequiredId.value.drawId)
      RequiredId.value.userId = toNumber(RequiredId.value.userId)
      if (RequiredId.value.helpSource !== 6) {
        RequiredId.value.getNums = 1
      }
      const params = {
        ...RequiredId.value,
      }
      // console.log(params)

      PostSenddrawchanceData(params).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('发送成功')
          dialogViewDetails.value = false
          GetDataList()
        }
        else {
          ElMessage.error(`发送失败${res.errors}`)
        }
      })
    }
  })
}

// 作废
function Delete(id: number) {
  ElMessageBox.confirm(
    '你确定要作废该抽奖机会吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      PostDeleteData(id).then((res: any) => {
        if (res.succeeded) {
          ElMessage.success('作废成功')
          GetDataList()
        }
        else {
          ElMessage.error(`作废失败。${res.errors}`)
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消作废',
      })
    })
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}
function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
}

onMounted(async () => {
  GetDataList()
  GetUserData()
  RequiredId.value.drawId = route.query.drawId as string
  RequiredId.value.userId = route.query.UserId as string
})
</script>

<template>
  <div>
    <div class="bg-white p-5">
      <el-descriptions title="用户信息" :column="4">
        <el-descriptions-item label="用户ID">
          {{ userMessage.userId }}
        </el-descriptions-item>
        <el-descriptions-item label="用户昵称">
          {{ userMessage.userNickName }}
        </el-descriptions-item>
        <el-descriptions-item label="用户手机号">
          {{ userMessage.userPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="用户OpenId">
          {{ userMessage.scOpenId }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="来源用户ID">
                <el-input v-model="findFrom.FromUserId" placeholder="请输入来源用户ID" clearable />
              </el-form-item>
              <el-form-item label="来源订单号">
                <el-input v-model="findFrom.FromOrderNo" placeholder="请输入来源订单号" clearable />
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
            <el-button type="success" @click="OpenView">
              发送抽奖机会
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <el-table v-loading="loading" :data="dataList.list" stripe style="width: 100%;" border>
        <el-table-column align="center" prop="id" label="ID" width="100" />
        <el-table-column align="center" prop="drawId" label="活动ID" width="150" />
        <el-table-column align="center" prop="fromSubscriberInfo.userNickName" label="助力人信息" width="200">
          <template #default="scope">
            <div v-if="!scope.row.fromSubscriberInfo">
              未授权
            </div>
            <div v-else class="user-name">
              <el-avatar :size="40" style="margin-right: 10px;" :src="scope.row.fromSubscriberInfo?.userAvatar" />
              <div>
                <p style="margin: 0;">
                  {{ scope.row.fromSubscriberInfo?.userNickName }}
                </p>
                <span>
                  {{ scope.row.fromSubscriberInfo?.userPhone }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column header-align="center" prop="fromSubscriberInfo.scOpenId" label="助力人OpenId" width="400">
          <template #default="scope">
            <div class="from-user-id">
              <p>助力人ID：{{ scope.row.fromSubscriberInfo?.userId }}</p>
              <p>助力人OpenId：{{ scope.row.fromSubscriberInfo?.scOpenId }}</p>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="fromUserid" label="助力人" width="150" /> -->
        <el-table-column align="center" prop="helpSource" label="助力途径" width="160">
          <template #default="scope">
            <el-tag>
              {{ scope.row.helpSource === 1 ? '邀请好友'
                : scope.row.helpSource === 2 ? '加企微'
                  : scope.row.helpSource === 3 ? '订单'
                    : scope.row.helpSource === 4 ? '邀请好友下单'
                      : scope.row.helpSource === 5 ? '扫大屏'
                        : scope.row.helpSource === 6 ? '完成任务奖励'
                          : scope.row.helpSource === 7 ? '新用户免费抽奖' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="fromOrderNo" label="助力人对应订单号" width="230" />
        <el-table-column align="center" prop="getNums" label="发送次数" width="150" />
        <el-table-column align="center" prop="flag" label="状态" width="120">
          <template #default="scope">
            <el-tag>
              {{ scope.row.flag === 1 ? '赠送'
                : scope.row.flag === 2 ? '退款'
                  : scope.row.flag === -10 ? '待生效' : '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="addTime" label="添加时间" min-width="220" />
        <el-table-column align="center" label="操作" fixed="right" min-width="200">
          <template #default="scope">
            <el-button v-if="scope.row.canCancellation && scope.row.getNums > 0" type="danger" :disabled="!scope.row.canCancellation || scope.row.getNums < 0" @click="Delete(scope.row.id)">
              作废此次抽奖机会
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
    <el-dialog v-model="dialogViewDetails" title="配置" width="450">
      <el-form
        ref="ruleFormRef"
        :model="RequiredId"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="用户ID" :prop="RequiredId.helpSource === 6 ? 'userId' : ''">
          <el-input v-model="RequiredId.userId" placeholder="请输入用户ID" type="number" disabled />
        </el-form-item>
        <el-form-item label="抽奖活动ID" prop="drawId">
          <el-input v-model="RequiredId.drawId" placeholder="请输入抽奖活动ID" type="number" disabled />
        </el-form-item>
        <el-form-item label="来源">
          <el-select v-model="RequiredId.helpSource" placeholder="请选择来源">
            <el-option label="订单（本人发一次）" :value="3" />
            <el-option label="邀请好友下单（每人各发一次）" :value="4" />
            <el-option label="直接赠送" :value="6" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="RequiredId.helpSource !== 6" label="订单编号" prop="orderNo">
          <el-input v-model="RequiredId.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item v-if="RequiredId.helpSource === 6" label="抽奖次数" prop="getNums">
          <el-input v-model="RequiredId.getNums" placeholder="请输入发送次数" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogViewDetails = false">
            取消
          </el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: left;

  div {
    text-align: left;
  }
}

.from-user-id {
  p {
    margin: 0;
  }
}
</style>
